<template>
    <div>
    <!-- 卡片视图 -->
    <el-card>
      <el-row>
        <el-col>
        <el-button type="primary" @click="addUserDialogForm()">添加用户</el-button>
      </el-col>
      </el-row>
      <br>
      <el-table :data="rolesList" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row :class="['bdbottom', i1 === 0 ? 'bdtop':'','vcenter']" v-for="(item1, i1) in scope.row.children" :key="item1.id">
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeTagById(scope.row, item1.id)">{{item1.authName}}</el-tag>
            <!-- <pre>{{item1}}</pre> -->
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级和三级权限 -->
              <el-col :span="19">
               <!-- eslint-disable-next-line vue/no-unused-vars -->
               <!-- 通过 for循环，渲染二级权限 -->
                <el-row :class="[i2 === 0 ? '' :'bdtop', 'vcenter']" v-for="(item2, i2) in item1.children" :key="item2.id">
                  <el-col :span="6">
                    <el-tag type="success" closable @close="removeTagById(scope.row, item2.id)">{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                </el-col>
                  <!-- <pre>{{item2}}</pre> -->
                  <!-- 渲染三级权限 -->
                  <el-col :span="18">
                   <!-- eslint-disable-next-line vue/no-unused-vars -->
                        <el-tag type="warning" v-for="(item3, i3) in item2.children" :key="item3.id" closable @close="removeTagById(scope.row, item3.id)">{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <!-- <pre>{{scope.row}}</pre> -->
          </template>
        </el-table-column>
        
        <el-table-column label="ID" type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <!-- eslint-disable-next-line vue/no-unused-vars -->
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini">编辑</el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini">删除</el-button>
            <el-button type="warning" icon="el-icon-setting" size="mini" @click="showRightsDialog(scope.row)">分配角色</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 权限列表Tree对话框开始 -->
    <el-dialog title="提示" :visible.sync="showRightsDialogVisible" width="50%" @close="setRightsDialogClosed">
      <!-- 树形控件 -->
  <el-tree :data="rightsList" :props="treeProps" show-checkbox node-key='id' default-expand-all :default-checked-keys='defKeys' ref='treeRefs'></el-tree>
  <span slot="footer" class="dialog-footer">
    <el-button @click="showRightsDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="allotRights">确 定</el-button>
  </span>
</el-dialog>
<!-- 权限列表Tree对话框结束 -->
<!-- 添加用户角色对话框 -->
<el-dialog title="添加用户" :visible.sync="addUserDialogVisible" width="50%" @close = "addRoleDialogClosed">
  <el-form ref="addRoleFormRef" :model="addRoleForm" :rules="addRoleFormRules" label-width="100px">
  <el-form-item label="用户名称:" prop="roleName">
    <el-input v-model="addRoleForm.roleName"></el-input>
  </el-form-item>
  <el-form-item label="用户描述:" prop="roleDesc">
    <el-input v-model="addRoleForm.roleDesc"></el-input>
  </el-form-item>
  </el-form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="addUserDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="addUser()">确 定</el-button>
  </span>
</el-dialog>
    </div>
</template>
<script>
export default {
  data () {
    return {
      // 所有角色列表数据
      rolesList: [
        {
          ID:1,
          roleName:'超级管理员',
          roleDesc:'',
        },
         {
          ID:2,
          roleName:'管理员',
          roleDesc:'',
        },
         {
          ID:3,
          roleName:'供货商',
          roleDesc:'',
        }
      ],
      // 控制分配权限对话框的显示与隐藏
      showRightsDialogVisible: false,
      // 所有权限数据
      rightsList: [
        {
          id:1,
          authName:'管理员',
          children:[{
            id:1,
          authName:'超级管理员',
          },
          {
            id:1,
          authName:'普通管理员',
          }]
        },
        {
          id:2,
          authName:'公司',
          children:[{
            id:1,
          authName:'部门',
          },
          {
            id:1,
          authName:'产品经理',
          },
          {
            id:2,
          authName:'销售经理',
          }]
        },
      ],
      // 树形控件的属性绑定对象
      treeProps: {
        children: 'children',
        label: 'authName'
      },
      defKeys: [],
      // 添加用户角色对话框显示与隐藏
      addUserDialogVisible: false,
      // 添加用户角色验证规则
      addRoleFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ]
      },
      addRoleForm: {
        roleName: '',
        roleDesc: ''
      }
    }
  },
  created () {
    this.getRolesList()
  },
  methods: {
    async getRolesList () {
      const { data: res } = await this.$http.get('roles')
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败')
      }
      this.rolesList = res.data
      // console.log(this.rolesList)
    },
    // 删除权限列表
    async removeTagById (role, rightId) {
      // console.log(rightId)
      // console.log(role)
      // 弹框提示用户是否删除
      const confirmResult = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('取消删除')
      }
      // console.log('确认删除')
      // 访问路径用`反撇号号
      const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('删除权限失败')
      }
      role.children = res.data
    },
    //  展示分配权限列表对话框
     showRightsDialog (role) {
      this.roleId = role.id
      // const { data: res } = await this.$http.get('rights/tree')
      // // console.log(res)
      // this.rightsList = res.data
      // this.getLeafKeys(role, this.defKeys)
      this.showRightsDialogVisible = true
    },
    // 通过递归形式角色下所有三级权限的ID，并保存到数组中
    getLeafKeys (node, arr) {
      // 如果当前node节点不包含children属性，则是三级节点
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => this.getLeafKeys(item, arr))
    },
    setRightsDialogClosed () {
      this.defKeys = []
    },
    // 点击确定，分配权限功能
    async allotRights () {
      const keys = [
        ...this.$refs.treeRefs.getCheckedKeys(),
        ...this.$refs.treeRefs.getHalfCheckedKeys()
      ]
      // console.log(this.$refs.treeRefs.getCheckedKeys())
      // console.log(keys)
      const idStr = keys.join(',')
      // console.log(idStr)
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: idStr })
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('分配权限失败')
      }
      this.getRolesList()
      this.showRightsDialogVisible = false
    },
    // 添加用户角色按钮
    addUserDialogForm () {
      this.addUserDialogVisible = true
    },
    // 提交用户角色
    addUser () {
      this.$refs.addRoleFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post('roles/', this.addRoleForm)
        // console.log(res)
        if (res.meta.status !== 201) {
          return this.$message.error('提交角色失败')
        }
        this.$message.success('提交角色成功')
        this.getRolesList()
        this.addUserDialogVisible = false
      })
    },
    // 用户角色对话框关闭信息重置
    addRoleDialogClosed () {
      this.$refs.addRoleFormRef.resetFields()
    }
  }
}
</script>
<style  scoped>
  .el-tag{
    margin: 7px;
  }
  .bdtop{
    border-top:1px solid #eee;
  }
  .bdbottom{
    border-bottom:1px solid #eee;
  }
  .vcenter{
    display: flex;
    align-items: center;
  }
</style>
